package com.xjrsoft.module.base.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xjrsoft.common.Enum.DeleteMarkEnum;
import com.xjrsoft.common.Enum.EnabledMarkEnum;
import com.xjrsoft.core.tool.utils.DigestUtil;
import com.xjrsoft.core.tool.utils.StringUtil;
import com.xjrsoft.module.base.dto.WeChatDepartDto;
import com.xjrsoft.module.base.dto.WeChatUserDto;
import com.xjrsoft.module.base.entity.XjrBaseDepartment;
import com.xjrsoft.module.base.entity.XjrBaseUser;
import com.xjrsoft.module.base.entity.XjrBaseUserRelation;
import com.xjrsoft.module.base.service.*;
import com.xjrsoft.module.base.utils.ListUtils;
import com.xjrsoft.module.base.utils.WeChatUtil;
import com.xjrsoft.module.base.vo.PageInfoVo;
import com.xjrsoft.module.base.vo.SynchronizationVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Scope("prototype")
public class XjrBaseWeChatServiceImpl implements IXjrBaseWeChatService {

    private List<WeChatDepartDto> deptBaseResponselist = new ArrayList<>();

    @Autowired
    private IXjrBaseDepartmentService iXjrBaseDepartmentService;

    @Autowired
    private IXjrBaseUserService iXjrBaseUserService;

    @Autowired
    private IXjrBaseUserRelationService iXjrBaseUserRelationService;

    @Autowired
    private WeChatUtil weChatUtil;

    @Autowired
    private IXjrBaseCompanyService iXjrBaseCompanyService;


    @Override
    public Boolean updateInfo(String companyId) throws Exception {
        deptBaseResponselist.clear();
        this.getdept(null);
        return this.updatedepart(companyId);
    }

    //更新部门信息
    private Boolean updatedepart(String companyId) throws Exception {
        List<XjrBaseDepartment> baseDepartments = iXjrBaseDepartmentService.list(Wrappers.<XjrBaseDepartment>query().lambda().eq(XjrBaseDepartment::getCompanyId, companyId).eq(XjrBaseDepartment::getDeleteMark, DeleteMarkEnum.NODELETE.getCode()).eq(XjrBaseDepartment::getEnabledMark, EnabledMarkEnum.ENABLED.getCode()));
        ArrayList<XjrBaseDepartment> updateDeparts = new ArrayList<>();
        ArrayList<XjrBaseDepartment> addDeparts = new ArrayList<>();
        out:for (WeChatDepartDto weChatDepartDto : deptBaseResponselist) {
            for (int i = 0; i < baseDepartments.size(); i++) {
                XjrBaseDepartment baseDepartment = baseDepartments.get(i);
                if (baseDepartment.getDepartmentId().equals(weChatDepartDto.getId().toString())) {
                    baseDepartment.setFullName(weChatDepartDto.getName()).setParentId(weChatDepartDto.getParentid().toString());
                    updateDeparts.add(baseDepartment);
                    continue out;
                }
            }
                    XjrBaseDepartment xjrBaseDepartment = new XjrBaseDepartment();
                    xjrBaseDepartment.setDepartmentId(weChatDepartDto.getId().toString()).setCompanyId(companyId)
                            .setFullName(weChatDepartDto.getName()).setParentId(weChatDepartDto.getParentid().toString())
                            .setDeleteMark(DeleteMarkEnum.NODELETE.getCode()).setEnabledMark(EnabledMarkEnum.ENABLED.getCode());
                    addDeparts.add(xjrBaseDepartment);
        }
        try {
            iXjrBaseDepartmentService.saveBatch(addDeparts);
            iXjrBaseDepartmentService.updateBatchById(updateDeparts);
        }catch (DuplicateKeyException e){
        throw  new Exception("用户和部门信息已更新到其他公司中!!!");
        }

        //更新用户信息
        Set<WeChatUserDto> userResponses = new HashSet<>();
        //微信中的用户信息
        for (WeChatDepartDto weChatDepartDto : deptBaseResponselist) {
            userResponses.addAll(weChatUtil.getDepartmentUser(Long.valueOf(weChatDepartDto.getId())));
        }
        userResponses = userResponses.stream().filter(s -> StringUtil.isNotBlank(s.getMobile())).collect(Collectors.toSet());
        //获取数据库中的用户信息
        List<XjrBaseUser> dbUsers = iXjrBaseUserService.list(Wrappers.<XjrBaseUser>query().lambda().eq(XjrBaseUser::getEnabledMark,EnabledMarkEnum.ENABLED.getCode()).eq(XjrBaseUser::getDeleteMark,DeleteMarkEnum.NODELETE.getCode()));
        Map<String, XjrBaseUser> dbUsersMap = dbUsers.stream().collect(Collectors.toMap(v -> v.getMobile(), v -> v));
        Map<String, WeChatUserDto> userResponsesMap = new HashMap<>();
        if (userResponses.size() > 0) {
            userResponsesMap = userResponses.stream().collect(Collectors.toMap(v -> v.getMobile(), v -> v));
        }

        ArrayList<XjrBaseUserRelation> addRelations = new ArrayList<>();
        //更新用户
        ArrayList<XjrBaseUser> updateBaseUsers = new ArrayList<>();
        Set<String> distinctIds = CollUtil.intersectionDistinct(dbUsersMap.keySet(), userResponsesMap.keySet());
        if (distinctIds.size() > 0) {
            for (String distinctId : distinctIds) {
                XjrBaseUser baseUser = dbUsersMap.get(distinctId);
                WeChatUserDto weChatUserDto = userResponsesMap.get(distinctId);
                baseUser.setRealName(weChatUserDto.getName()).setHeadIcon(weChatUserDto.getAvatar()).setGender(Integer.valueOf(weChatUserDto.getGender()))
                        .setEmail(weChatUserDto.getEmail()).setCompanyId(companyId).setModifyDate(LocalDateTimeUtil.now()).setWeChatId(weChatUserDto.getUserid());
                List<XjrBaseUserRelation> list = iXjrBaseUserRelationService.list(Wrappers.<XjrBaseUserRelation>query().lambda().eq(XjrBaseUserRelation::getCategory, 3).eq(XjrBaseUserRelation::getUserId, baseUser.getUserId()).eq(XjrBaseUserRelation::getObjectId, weChatUserDto.getDepartment().get(0).toString()));
                updateBaseUsers.add(baseUser);
                if(list==null||list.size()<=0) {
                    XjrBaseUserRelation xjrBaseUserRelation = new XjrBaseUserRelation();
                    xjrBaseUserRelation.setUserId(baseUser.getUserId()).setObjectId(weChatUserDto.getDepartment().get(0).toString()).setCategory(3).setCreateDate(LocalDateTimeUtil.now());
                    addRelations.add(xjrBaseUserRelation);
                }
            }
        }

        //添加数据库中没有的用户
        List<String> subtractIds2 = CollUtil.subtractToList(userResponsesMap.keySet(), dbUsersMap.keySet());
        if (subtractIds2.size() > 0) {
            for (String subtractId : subtractIds2) {
                XjrBaseUser baseUser = new XjrBaseUser();
                WeChatUserDto weChatUserDto = userResponsesMap.get(subtractId);
                baseUser.setAccount(weChatUserDto.getMobile()).setPassword(DigestUtil.encrypt("000000")).setRealName(weChatUserDto.getName()).setHeadIcon(weChatUserDto.getAvatar()).setEmail(weChatUserDto.getEmail()).setMobile(weChatUserDto.getMobile())
                        .setCompanyId(companyId).setEnabledMark(EnabledMarkEnum.ENABLED.getCode()).setDeleteMark(DeleteMarkEnum.NODELETE.getCode()).setCreateDate(LocalDateTimeUtil.now()).setWeChatId(weChatUserDto.getUserid());
                iXjrBaseUserService.save(baseUser);
                    XjrBaseUserRelation xjrBaseUserRelation = new XjrBaseUserRelation();
                    xjrBaseUserRelation.setUserId(baseUser.getUserId()).setObjectId(weChatUserDto.getDepartment().get(0).toString()).setCategory(3).setCreateDate(LocalDateTimeUtil.now());
                    addRelations.add(xjrBaseUserRelation);
            }
        }
        iXjrBaseUserService.updateBatchById(updateBaseUsers);
        iXjrBaseUserRelationService.saveBatch(addRelations);
        return true;
    }

    //拉取所有部门id
    private void getdept(Long dept_id) {
        List<WeChatDepartDto> departmentList = weChatUtil.getDepartmentList(dept_id);
        deptBaseResponselist.addAll(departmentList);
    }




    //分页查询
    @Override
    public PageInfoVo getList(String keyword, Integer page, Integer pageSize,String companyId) {
        ArrayList<SynchronizationVo> synchronizationVos = new ArrayList<>();
        List<XjrBaseDepartment> baseDepartments = iXjrBaseDepartmentService.list(Wrappers.<XjrBaseDepartment>query().lambda().eq(XjrBaseDepartment::getCompanyId, companyId).eq(XjrBaseDepartment::getDeleteMark, DeleteMarkEnum.NODELETE.getCode()).eq(XjrBaseDepartment::getEnabledMark, EnabledMarkEnum.ENABLED.getCode()));
        Set<String> departmentIds = baseDepartments.stream().map(XjrBaseDepartment::getDepartmentId).collect(Collectors.toSet());
        for (XjrBaseDepartment xjrBaseDepartment : baseDepartments) {
            SynchronizationVo synchronizationVo = new SynchronizationVo();
            synchronizationVo.setName(xjrBaseDepartment.getFullName());
            synchronizationVo.setStatus(1);
            synchronizationVo.setInfo("部门信息更新成功");
            synchronizationVos.add(synchronizationVo);
        }
        Set<XjrBaseUserRelation> xjrBaseUserRelations=new HashSet<>();
        if(departmentIds.size()>1000){
            int i = departmentIds.size() / 1000;
            for (int j = 0; j <=i ; j++) {
                ArrayList<String> ids = new ArrayList<>();
                if(j==i){
                    ids.addAll(CollectionUtil.sub(departmentIds, 1000 * j,departmentIds.size()));
                }else {
                    ids.addAll(CollectionUtil.sub(departmentIds, 1000 * j, 1000 * (j + 1)));
                }
               xjrBaseUserRelations.addAll(iXjrBaseUserRelationService.list(Wrappers.<XjrBaseUserRelation>query().lambda().eq(XjrBaseUserRelation::getCategory, 3).in(CollectionUtil.isNotEmpty(ids), XjrBaseUserRelation::getObjectId, ids)));
            }
        }else {
            xjrBaseUserRelations.addAll(iXjrBaseUserRelationService.list(Wrappers.<XjrBaseUserRelation>query().lambda().eq(XjrBaseUserRelation::getCategory, 3).in(CollectionUtil.isNotEmpty(departmentIds), XjrBaseUserRelation::getObjectId, departmentIds)));
        }
        Set<String> dbUserIds = xjrBaseUserRelations.stream().map(XjrBaseUserRelation::getUserId).collect(Collectors.toSet());
        if(dbUserIds!=null&&dbUserIds.size()>0) {
            List<XjrBaseUser> xjrBaseUsers = iXjrBaseUserService.listByIds(dbUserIds);
            for (XjrBaseUser xjrBaseUser : xjrBaseUsers) {
                SynchronizationVo synchronizationVo = new SynchronizationVo();
                synchronizationVo.setName(xjrBaseUser.getRealName());
                synchronizationVo.setStatus(1);
                synchronizationVo.setInfo("员工信息更新成功");
                synchronizationVos.add(synchronizationVo);
            }
        }
        if(!StringUtil.isBlank(keyword)){
           List<SynchronizationVo> SynchronizationVoList = ListUtils.seach(synchronizationVos, keyword);
           return ListUtils.Pager(pageSize, page, SynchronizationVoList);
       }else {
           return ListUtils.Pager(pageSize, page, synchronizationVos);
       }
    }
}
